package fun.qu_an.minecraft.gitfetch;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Getter;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.WorldSavePath;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.URIish;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;

public class GitFetchConfig {
	private static final Gson GSON = new GsonBuilder().setVersion(1.0).disableHtmlEscaping().setPrettyPrinting().setLenient().create();
	private static final Path configPath = FabricLoader.getInstance().getConfigDir().resolve(GitFetch.MOD_ID + ".json");
	@Getter
	private static final GitFetchConfig instance = new GitFetchConfig();
	@Getter
	private final GitFetchJsonConfig jsonConfig = new GitFetchJsonConfig();
	@Getter
	private Git git = null;

	public static boolean reload(MinecraftServer server) throws IOException, URISyntaxException, GitAPIException {
		if (!Files.exists(configPath)) {
			Files.createDirectories(configPath.getParent());
			Files.createFile(configPath);
			Files.writeString(configPath, GSON.toJson(instance.jsonConfig));
		} else if (Files.isDirectory(configPath)) {
			Files.delete(configPath);
			Files.createFile(configPath);
			Files.writeString(configPath, GSON.toJson(instance.jsonConfig));
		} else if (Files.size(configPath) == 0) {
			Files.writeString(configPath, GSON.toJson(instance.jsonConfig));
		}
		GitFetchJsonConfig newCfg = GSON.fromJson(Files.readString(configPath), GitFetchJsonConfig.class);
		instance.jsonConfig.url = newCfg.url;
		instance.jsonConfig.branch = newCfg.branch;
		instance.jsonConfig.datapack = newCfg.datapack;
		instance.jsonConfig.username = newCfg.username;
		instance.jsonConfig.password = newCfg.password;
		if (newCfg.url.isBlank() || newCfg.branch.isBlank() || newCfg.datapack.isBlank()) {
			return false;
		}
		instance.git = Git.open(server.getSavePath(WorldSavePath.DATAPACKS).resolve(newCfg.datapack).toFile());
		instance.git.remoteAdd().setUri(new URIish(newCfg.url)).call();
		return true;
	}

	@Getter
	public static class GitFetchJsonConfig {
		private String url = "";
		private String branch = "main";
		private String datapack = "";
		private String username = "";
		private String password = "";
	}
}
